package ext.generic.integration.sourcing.service;

import java.util.Enumeration;

import wt.fc.WTObject;
import wt.part.WTPart;

import com.infoengine.object.IeObject;
import com.infoengine.object.factory.Group;

import ext.generic.integration.sourcing.task.TwoLevelMaterialTask;
import ext.tianma.part.forms.TMTypeUtil;

public class TwoLevelMaterialService {
	
	/**
	 * 往中间表添加或者更新数据
	 * 针对单独的二级物料
	 * @param wtObject
	 * @return boolean
	 */
	public static boolean releasePart( WTObject wtObject ){
		
		boolean releaseFlag = false;
		if( wtObject == null ){
			return releaseFlag;
		}
		
		WTPart part = null;
		
		if( wtObject instanceof WTPart ){
			part = ( WTPart )wtObject;
		}
		
		if( part != null ){
			
			if( TMTypeUtil.isTwoLevelMaterial( part ) ){
				releaseFlag = TwoLevelMaterialTask.add( part,"" );
			}
		}
		return releaseFlag;
	}
	
	/**
	 * 从数据库中获取物料的发布状态
	 * @param wtObject
	 * @return
	 */
	public static String updateReleaseState( WTObject wtObject ){	
		String releaseState = "";
		
		if( wtObject == null ){
			return releaseState;
		}
		
		WTPart part = null;
		
		if( wtObject instanceof WTPart ){
			part = ( WTPart )wtObject;
		}
		
		if( part != null ){
			
			if( TMTypeUtil.isTwoLevelMaterial( part ) ){
				Group group = TwoLevelMaterialTask.query( part );
				releaseState = updateReleaseState( group );
			}
			
		}
		
		return releaseState;	
	}

	private static String updateReleaseState(Group group) 
	{		
		String releaseState = "";
		
		if( group == null ){
			return releaseState;
		}
		
		Enumeration enumeration = group.getGroup().getChildren();
		IeObject ieoRecord = null;
		if( enumeration != null ){
			
			while( enumeration.hasMoreElements() ){
				ieoRecord = (IeObject)enumeration.nextElement();
				
				if( ieoRecord != null ){
					releaseState = ieoRecord.getAtt("flag").getDatum().toString();
				}
			}
		}
		
		return releaseState;
	}
}
